package org.stormphoenix.bbsfamily.dao

import org.apache.ibatis.annotations.*
import org.apache.ibatis.mapping.FetchType
import org.springframework.stereotype.Component
import org.stormphoenix.bbsfamily.entity.RoleDO

@Mapper
@Component
interface RoleMapper {

    /**
     * 不仅仅是这里，其他地方的多对多属性也使用了 fetchType = FetchType.EAGER
     * 这里可能会影响性能。但如果修改成 fetchType = FetchType.LAZY 就会报错，因为返回值是 kotlin 的
     * data class，而 data class 是 final 类型，无法被继承，这样就导致 mybatis 无法创建该属性的代理（Proxy）
     *
     * 目前没想到有什么解决方案 ^_^
     */

    @Select("SELECT * FROM role WHERE id = #{id}")
    @Results(
        Result(id = true, column = "id", property = "id"),
        Result(
            column = "id",
            property = "authorities",
            many = Many(
                select = "org.stormphoenix.bbsfamily.dao.AuthorityMapper.findAuthoritiesByRoleId",
                fetchType = FetchType.EAGER
            )
        )
    )
    fun findRoleById(@Param(value = "id") id: Long): RoleDO?

    @Select("SELECT * FROM role WHERE id IN (SELECT role_id FROM user_role WHERE user_id = #{userId})")
    @Results(
        Result(id = true, column = "id", property = "id"),
        Result(
            column = "id",
            property = "authorities",
            many = Many(
                select = "org.stormphoenix.bbsfamily.dao.AuthorityMapper.findAuthoritiesByRoleId",
                fetchType = FetchType.EAGER
            )
        )
    )
    fun findRolesByUserId(@Param(value = "userId") userId: Long): List<RoleDO>?
}